package wang.lcs.pay.ali;

import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.fasterxml.jackson.core.JsonProcessingException;

import wang.lcs.pay.ali.dto.AliCreateAppResponse;
import wang.lcs.pay.config.AlipayConfig;
import wang.lcs.pay.ex.HttpRequestException;

@Controller
@RequestMapping("/ali")
public class CreateOrderController {

    private static final Logger log = LoggerFactory.getLogger(CreateOrderController.class);

    @Resource
    AlipayConfig config;
    @Resource
    AlipayClient client;

    @RequestMapping(value = "/create/web", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String createWapOrder(AlipayTradePagePayModel model) throws JsonProcessingException, AlipayApiException {
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        AlipayTradePagePayRequest ali = new AlipayTradePagePayRequest();
        ali.setReturnUrl(config.getReturnUrl());
        ali.setNotifyUrl(config.getNotifyUrl());
        ali.setBizModel(model);

        String form = client.pageExecute(ali).getBody();
        log.debug(form);
        return String.format("<html><head></head><body> %s </body></html>", form);
    }

    @RequestMapping(value = "/create/wap", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String createWebOrder(AlipayTradeWapPayModel model) {
        // 销售产品码 必填
        model.setProductCode("QUICK_WAP_WAY");
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

        alipay_request.setBizModel(model);
        alipay_request.setNotifyUrl(config.getNotifyUrl());
        alipay_request.setReturnUrl(config.getReturnUrl());
        try {
            String form = client.pageExecute(alipay_request).getBody();
            log.debug("URL: {}", form);
            return String.format("<html><head></head><body> %s </body></html>", form);
        } catch (AlipayApiException e) {
            throw new HttpRequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

    // https://docs.open.alipay.com/api_1/alipay.trade.app.pay
    @RequestMapping(value = "/create/app")
    @ResponseBody
    public AliCreateAppResponse createAppOrder(AlipayTradeAppPayModel model) {
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        if (model.getSellerId() != null && request.getNotifyUrl() != null) {
            throw new HttpRequestException("Not set seller-id, notify-url!");
        }
        if (model.getOutTradeNo() == null) {
            // "80\\d{3}-\\d{8}-\\d{8}"
            model.setOutTradeNo(UUID.randomUUID().toString());
        }
        try {
            AlipayTradeAppPayResponse response = client.sdkExecute(request);
            System.out.println(response.getBody());// 就是orderString 可以直接给客户端请求，无需再做处理。
            AliCreateAppResponse rqu = new AliCreateAppResponse();
            rqu.setRequest(response.getBody());
            log.debug("Request: {}", rqu.getRequest());
            return rqu;
        } catch (AlipayApiException e) {
            throw new HttpRequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}
